package cn.jishiyu11.xeqb.webview

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.text.format.DateUtils
import android.view.KeyEvent
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView

import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.umeng.analytics.MobclickAgent

import java.io.File
import java.io.IOException

import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.base.BaseActivity
import cn.jishiyu11.xeqb.utils.*

/**
 * Created by vvguoliang on 2017/7/3.
 *
 *
 * X5核浏览器
 */

class X5WebViewActivity : BaseActivity(), View.OnClickListener {

    private var webview: WebView? = null

    private var url: String? = ""

    private var banner_progressBar: ProgressBar? = null

    private var title_view: TextView? = null

    private var banner_linear: LinearLayout? = null

    private val webViewClient = object : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, pl: String?): Boolean {
            if (url!!.startsWith("http") || url!!.startsWith("https")) { //http和https协议开头的执行正常的流程
                return false
            } else {
                //其他的URL则会开启一个Acitity然后去调用原生APP
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                if (intent.resolveActivity(packageManager) == null) {
                    //说明系统中不存在这个activity
                } else {
                    //如果想要加载成功跳转可以 这样
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
                    startActivity(intent)
                }
                return true
            }


        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            val title = view!!.title
            if (TextUtils.isEmpty(title)
                    || title.contains("404")
                    || title.contains("找不到")
                    || title.contains("无法打开")) {
                title_view!!.text = title
                banner_linear!!.visibility = View.VISIBLE
//                fail_linear!!.visibility = View.VISIBLE
            } else {
                banner_linear!!.visibility = View.VISIBLE
                title_view!!.text = title
            }
        }

        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            super.onReceivedError(view, errorCode, description, failingUrl)
        }
    }

    private val webChromeClient = object : WebChromeClient() {

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            if (TextUtils.isEmpty(title)
                    || title!!.contains("404")
                    || title.contains("找不到")
                    || title.contains("无法打开")) {
                title_view!!.text = title
                banner_linear!!.visibility = View.GONE
//                fail_linear!!.visibility = View.VISIBLE

            } else {
                //                view.setVisibility(View.VISIBLE);
                banner_linear!!.visibility = View.VISIBLE
                title_view!!.text = view!!.title
            }
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            banner_progressBar!!.progress = newProgress
            if (newProgress == 100) {
                banner_progressBar!!.visibility = View.GONE
                var u = view?.url
                println(u)
            } else {
                banner_progressBar!!.visibility = View.VISIBLE
                view!!.visibility = View.VISIBLE
            }
        }
//
//        //For Android 3.0+
//        fun openFileChooser(uploadMsg: ValueCallback<Uri>) {
//            selectImage()
//            mUM = uploadMsg
//            val i = Intent(Intent.ACTION_GET_CONTENT)
//            i.addCategory(Intent.CATEGORY_OPENABLE)
//            i.type = "*/*"
//            this@X5WebViewActivity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR)
//        }
//
//        // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
//        fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String) {
//            selectImage()
//            mUM = uploadMsg
//            val i = Intent(Intent.ACTION_GET_CONTENT)
//            i.addCategory(Intent.CATEGORY_OPENABLE)
//            i.type = "*/*"
//            this@X5WebViewActivity.startActivityForResult(
//                    Intent.createChooser(i, "File Browser"),
//                    FCR)
//        }
//
//        //For Android 4.1+
//        override fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String?, capture: String?) {
//            selectImage()
//            mUM = uploadMsg
//            val i = Intent(Intent.ACTION_GET_CONTENT)
//            i.addCategory(Intent.CATEGORY_OPENABLE)
//            i.type = "*/*"
//            this@X5WebViewActivity.startActivityForResult(Intent.createChooser(i, "File Chooser"), X5WebViewActivity.FCR)
//        }
//
//        //For Android 5.0+
//        override fun onShowFileChooser(
//                webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?,
//                fileChooserParams: WebChromeClient.FileChooserParams?): Boolean {
//            selectImage()
//            if (mUMA != null) {
//                mUMA!!.onReceiveValue(null)
//            }
//            mUMA = filePathCallback
//            var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//            if (takePictureIntent!!.resolveActivity(this@X5WebViewActivity.packageManager) != null) {
//                var photoFile: File? = null
//                try {
//                    photoFile = createImageFile()
//                    takePictureIntent.putExtra("PhotoPath", mCM)
//                } catch (ex: IOException) {
//                    Log.e("TAG", "Image file creation failed", ex)
//                }
//
//                if (photoFile != null) {
//                    mCM = "file:" + photoFile.absolutePath
//                    filePath = photoFile.absolutePath
//                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile))
//                } else {
//                    takePictureIntent = null
//                }
//            }
//            val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
//            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
//            contentSelectionIntent.type = "*/*"
//            val intentArray: Array<Intent>
//            if (takePictureIntent != null) {
//                intentArray = arrayOf(takePictureIntent)
//            } else {
//                intentArray = arrayOf()
//            }
//
//            val chooserIntent = Intent(Intent.ACTION_CHOOSER)
//            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
//            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser")
//            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)
//            startActivityForResult(chooserIntent, FCR)
//            return true
//        }
    }

//    private var mCM: String? = null
//    private var filePath = ""
//    private var mUM: ValueCallback<Uri>? = null
//    private var mUMA: ValueCallback<Array<Uri>>? = null
//    internal var compressPath = ""

    override fun findViewById() {
        findViewById<View>(R.id.title_image).visibility = View.VISIBLE
        findViewById<View>(R.id.title_image).setOnClickListener(this)
        title_view = findViewById(R.id.title_view)
        webview = findViewById(R.id.banner_webview)
        webview!!.isHorizontalScrollBarEnabled = false
        webview!!.isVerticalScrollBarEnabled = false
        //下面方法去掉
        val ix5 = webview!!.x5WebViewExtension
        ix5?.setScrollBarFadingEnabled(false)

        banner_progressBar = findViewById(R.id.banner_progressBar)
        banner_linear = findViewById(R.id.banner_linear)
        webview!!.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            val uri = Uri.parse(url)

            val intent = Intent(Intent.ACTION_VIEW, uri)

            startActivity(intent)
        }

    }

    override fun initView() {
        webview!!.webViewClient = webViewClient
        webview!!.webChromeClient = webChromeClient


        if (!TextUtils.isEmpty(url) && "null" != url) {
            banner_linear!!.visibility = View.VISIBLE
            webview!!.loadUrl(url)
        } else {
            title_view!!.text = ""
            banner_linear!!.visibility = View.GONE
        }

    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.title_image -> finish()
        }
    }

    @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
    private fun getSettings() {
        //        webview.setLayerType( View.LAYER_TYPE_SOFTWARE, null ); //渲染加速器
        //        webview.getSettings().setRenderPriority( WebSettings.RenderPriority.HIGH ); //提高渲染的优先级
        //        webview.removeJavascriptInterface( "searchBoxJavaBridge_" ); //防止360
        val settings = webview!!.settings
        //        settings.setBlockNetworkImage( true );
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.saveFormData = false
        settings.domStorageEnabled = true
        settings.allowContentAccess = true
        settings.allowFileAccess = true
        settings.defaultTextEncodingName = "utf-8"
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        settings.cacheMode = WebSettings.LOAD_NO_CACHE //LOAD_NO_CACHE设置,缓存模式LOAD_DEFAULT

        if (Build.VERSION.SDK_INT >= 19) {
            settings.loadsImagesAutomatically = true
        } else {
            settings.loadsImagesAutomatically = false
        }
        settings.databaseEnabled = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //            settings.setMixedContentMode( WebSettings.MIXED_CONTENT_ALWAYS_ALLOW );
            settings.mixedContentMode = WebSettings.LOAD_NORMAL
        }
        webview!!.settings.blockNetworkImage = false

        webview!!.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            val uri = Uri.parse(url)

            val intent = Intent(Intent.ACTION_VIEW, uri)

            startActivity(intent)
        }

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (webview!!.canGoBack()) {
            webview!!.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)

    }

//    /**
//     * 打开图库,同时处理图片
//     */
//    private fun selectImage() {
//        compressPath = Environment.getExternalStorageDirectory().path + "/QWB/temp"
//        val file = File(compressPath)
//        if (!file.exists()) {
//            file.mkdirs()
//        }
//        compressPath = compressPath + File.separator + "compress.png"
//        val image = File(compressPath)
//        if (image.exists()) {
//            image.delete()
//        }
//    }

    // Create an image file
    @Throws(IOException::class)
    private fun createImageFile(): File {
        @SuppressLint("SimpleDateFormat") val timeStamp = DateUtils.formatElapsedTime(System.currentTimeMillis())
        val imageFileName = "img_" + timeStamp + "_"
        val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(imageFileName, ".jpg", storageDir)
    }

//    override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
//        super.onActivityResult(requestCode, resultCode, intent)
//        if (Build.VERSION.SDK_INT >= 21) {
//            var results: Array<Uri>? = null
//            //Check if response is positive
//            if (resultCode == Activity.RESULT_OK) {
//                if (requestCode == FCR) {
//                    if (null == mUMA) {
//                        return
//                    }
//                    if (intent == null) {
//                        //Capture Photo if no image available
//                        if (mCM != null) {
//                            // results = new Uri[]{Uri.parse(mCM)};
//                            results = arrayOf(afterChosePic(filePath, compressPath))
//                        }
//                    } else {
//                        val dataString = intent.dataString
//                        if (dataString != null) {
//                            results = arrayOf(Uri.parse(dataString))
//                            Log.d("tag", intent.toString())
//                            //                            String realFilePath = getRealFilePath(Uri.parse(dataString));
//                            //                            results = new Uri[]{afterChosePic(realFilePath, compressPath)};
//                        }
//                    }
//                }
//            }
//            mUMA!!.onReceiveValue(results)
//            mUMA = null
//        } else {
//            if (requestCode == FCR) {
//                if (null == mUM) return
//                val result = if (intent == null || resultCode != Activity.RESULT_OK) null else intent.data
//                mUM!!.onReceiveValue(result)
//                mUM = null
//            }
//        }
//    }


    /**
     * 选择照片后结束
     */
    private fun afterChosePic(oldPath: String, newPath: String): Uri {
        var newFile: File?
        try {
            newFile = FileUtils.compressFile(oldPath, newPath)
        } catch (e: Exception) {
            e.printStackTrace()
            newFile = null
        }

        return Uri.fromFile(newFile)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_webview)
        url = intent.extras!!.getString("url")

        if (!url.isNullOrEmpty()) {

                if (url!!.startsWith("http") || url!!.startsWith("https")) { //http和https协议开头的执行正常的流程
                    if (url!!.contains("?")) {
                        url = url + "&userNo=${USER_UserNo}&versionNo=${PhoneAppVersion}&deviceType=${DEVICETYPE}&appID=110&userID=$USER_UserNo"
                    } else {
                        url = url + "?userNo=${USER_UserNo}&versionNo=${PhoneAppVersion}&deviceType=${DEVICETYPE}&appID=110&userID=$USER_UserNo"
                    }
                }
        }
        findViewById()
        initView()
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }

    /**
     * 确保注销配置能够被释放
     */
    override fun onDestroy() {
        // TODO Auto-generated method stub
        if (webview != null) {
            webview!!.destroy()
        }
        super.onDestroy()
    }

    companion object {
        private val FCR = 1
    }
}
